import { Component, OnInit, ViewChild, ElementRef, Inject } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { config } from '../../shared/smartadmin.config'

declare var $: any
declare var BMap: any
declare var toWGS84: any
declare var toMapPoint: any
declare var Viewer: any;
@Component({
  selector: 'sa-repair-point',
  templateUrl: './repair-point.component.html',
  styleUrls: ['./repair-point.component.css']
})
export class RepairPointComponent implements OnInit {
  validatorOptions = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      repairPointName: {
        trigger: 'blur',
        validators: {
          // notEmpty: {
          //   message: '请输入站点名称'
          // },
          // stringLength: {
          //   max: 30,
          //   message: '站点名称30字以内'
          // },
          // remote: {
          //   message: '站点名称已存在,请输入新的站点名称',
          //   url: config.BaseURL + 'maintenance/verifyRepairPointName.html',
          //   data: function (validator) {
          //     return {
          //       id: validator.getFieldElements('repairPointName').attr('rowId')
          //     }
          //   }
          // },
          callback: {
            callback: function (value, validator, $field) {
              const length = value ? value.length : 0

              $('#hint').attr('style', 'display:none')

              if (!length) {
                return {
                  valid: false,
                  message: '请输入站点名称'
                }
              }
              if (length > 30) {
                return {
                  valid: false,
                  message: '站点名称30字以内'
                }
              }

              if (value.length > 10 && value.length <= 30) {
                $('#hint').attr('style', 'display:block')
              }
              return true
            }
          }
        }
      },
      companyName: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择服务厂区'
          }
        }
      },
      linkManInput: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请输入负责人'
          }
          // ,stringLength: {
          //     max: 10,
          //     message: '责任人10字以内'
          // },
        }
      },
      startTime: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择工作开始时间'
          }
        }
      },
      endTime: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择工作结束时间'
          }
        }
      },
      timeZone: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择维修时间区间'
          }
        }
      },
      linkPhone: {
        validators: {
          notEmpty: {
            message: '请输入联系电话'
          },
          integer: {
            message: '请输入数字电话号码'
          }
        }
      },
      address: {
        validators: {
          notEmpty: {
            message: '请输入地址'
          }
        }
      },
      radius: {
        validators: {
          integer: {
            message: '请输入数字围栏半径'
          }
        }
      },
      longitude: {
        validators: {
          callback: {
            callback: function (value, validator, $field) {
              if (value) {
                var reg = /^[-+]?(0(\.\d{1,10})?|([1-9](\d)?)(\.\d{1,10})?|1[0-7]\d{1}(\.\d{1,10})?|180\.0{1,10})$/
                const floatreg = /^(\d+)(.\d{0,7})?$/
                if (!reg.test(value)) {
                  return {
                    valid: false,
                    message: '经度有误'
                  }
                } else if (!floatreg.test(value)) {
                  return {
                    valid: false,
                    message: '最多可输入小数点后七位'
                  }
                } else {
                  return true
                }
              } else {
                return true
              }
            }
          }
        }
      },
      latitude: {
        validators: {
          callback: {
            callback: function (value, validator, $field) {
              if (value) {
                var reg = /^[-+]?((0|([1-8]\d?))(\.\d{1,10})?|90(\.0{1,10})?)$/
                const floatreg = /^(\d+)(.\d{0,7})?$/
                if (!reg.test(value)) {
                  return {
                    valid: false,
                    message: '纬度有误'
                  }
                } else if (!floatreg.test(value)) {
                  return {
                    valid: false,
                    message: '最多可输入小数点后七位'
                  }
                } else {
                  return true
                }
              } else {
                return true
              }
            }
          }
        }
      }
    }
  }
  tableData: any[] = [] //table数据
  totalCount: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数
  tableParam: any = {
    repairPointName: '',
    pointPersonnel: '',
    searchKey: '',
    // startTime: '',
    // endTime: '',
    status: '',
    companyId: '',
    companyName: '',
    provinceId: '',
    provinceName: ''
  }
  mapParam: any = {
    companyId: '',
    provinceId: ''
  }
  userList: any = [] // 项目实施人员
  repairPointList: any = [] // 站点名称
  pageType: string = '新增'
  repairPonitFrom: any = {
    id: undefined,
    repairPointName: '',
    warehouseId: '', // 非站点仓库
    companyArrays: [],
    companyId: '',
    userName: '',
    userId: '',
    linkMan: '',
    linkPhone: '',
    employNumber: '',
    startTime: '',
    endTime: '',
    address: '',
    lng: '',
    lat: '',
    repairInfo: [],
    radius: ''
  }
  // 添加时间段
  isOverSelectTime = false // 是否是全局的时间区间配置
  addStartTimeQuick = '' // 默认的快速添加的数量
  addStartTimeByHand = '' // 默认的添加开始时间
  addEndTimeByHand = '' // 默认的添加开始时间
  oneZoneCarNumByHand = '' // 默认的手动天机的车辆数量
  myTimezoneList = [] // 添加到这里的表单数据
  editOverall = false // 是否在展示的全局配置时间  是的话就显示的是重新配置按钮
  inputApi: string = 'maintenance/reginlist.html'
  constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.curPage = queryParams.nowPage || 1
    })
  }
  companySelected(data, type = 'table') {
    if (type == 'table') {
      this.tableParam.companyId = data.companyId || ''
      this.tableParam.companyName = data.companyName
    } else if (type == 'map') {
      this.mapParam.companyId = data.companyId || ''
    }
  }
  //区域
  regionSelected(data, type = 'table') {
    if (type == 'table') {
      this.tableParam.provinceId = data.companyId || ''
      this.tableParam.provinceName = data.companyName
    } else if (type == 'map') {
      this.mapParam.provinceId = data.companyId || ''
    }
  }
  // 确认选择服务厂区
  confirmCompanySelected(data) {
    this.repairPonitFrom.repairPointName = data.companyNameSelectedList.join('-')
    this.repairPonitFrom.companyId = data.companyIdSelectedList.join(',')

    $('#repairPointName').val(this.repairPonitFrom.repairPointName)
    $('#repairPointFrom').bootstrapValidator('revalidateField', $('#repairPointName'));

    // 手动触发repairPointName Input change事件
    const inputElement = document.getElementById('repairPointName')
    inputElement.dispatchEvent(new Event('change'))

    if (data.companyIdSelectedList.length > 0) {
      this.getAddressMsg(this.repairPonitFrom.companyId)
    } else {
      this.clearMarker('服务公司') //清空原有的定位数据
    }
  }

  // 站点名称input change事件
  inputChange(e) {
    const value = e.target.value

    const reqdata = {
      repairPointName: value,
      id: $('#repairPointName').attr('rowId')
    }
    this.jsonApiService.http_obj('maintenance/verifyRepairPointName.html', reqdata).subscribe(data => {
      if (!data.valid) {
        this.jsonApiService.message('站点名称重复，请重新输入')
        this.repairPonitFrom.repairPointName = ''
        $('#repairPointName').val(this.repairPonitFrom.repairPointName)
        $('#repairPointFrom').bootstrapValidator('revalidateField', $('#repairPointName'));
      }
    })
  }

  // 接收子组件传递过来的数据
  getSelectTableTime(time) {
    this.tableParam.startTime = time.startTime
    this.tableParam.endTime = time.endTime
  }
  // 非站点关联仓库列表
  warehouseList: any[] = []
  ngOnInit() {
    this.initBtn()
    System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
      System.import('assets/js/select2-zh-CN.js').then(() => {
        this.initAllUser().then(() => {
          this.initLinkManSelect2()
          this.initRepairUserSelect2()
        })
        this.initAllRepairPoint().then(() => {
          this.initRepairPointSelect2()
        })
      })
    })
    this.load()
    this.initMap()
    this.initTimeArr()
    this.getWarehouseList()
  }

  getWarehouseList() {
    this.jsonApiService.http_get('warehouse/getNoSiteWarehouse.html').subscribe(data => {
      if (data.success) {
        this.warehouseList = data.data
      }
    })
  }
  //table刷新
  refresh() {
    this.load()
  }
  //表格搜索
  tableSearch() {
    this.curPage = 1
    this.load()
  }
  //删除
  tableDel(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
      this.jsonApiService.http('maintenance/deleteBatch.html', 'id=' + row.id).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.load()
        }
      })
    })
  }
  //分页回调
  paginate(e) {
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }
  //初始化加载list数据
  load() {
    let timeCheck = common.correctTimeParams(this.tableParam.startTime, this.tableParam.endTime, 0)
    if (!timeCheck.status) {
      this.jsonApiService.message(timeCheck.message)
      return
    }
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        repairPointName: this.tableParam.repairPointName,
        companyId: this.tableParam.companyId,
        pointPersonnel: this.tableParam.pointPersonnel,
        startTime: this.tableParam.startTime,
        endTime: this.tableParam.endTime,
        status: this.tableParam.status,
        searchKey: common.stringTrim(this.tableParam.searchKey),
        provinceName: this.tableParam.provinceName,
        provinceId: this.tableParam.provinceId
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('maintenance/list.html', reqdata).subscribe(data => {
      if (data.isSuccess) {
        System.import('assets/js/bootstrap-switch.min.js').then(() => {
          System.import('assets/css/bootstrap-switch.min.css').then(() => {
            let timer1 = setTimeout(() => {
              this.initSwitch()
              clearTimeout(timer1)
              timer1 = null
            }, 0)
          })
        })
        for (let i = 0; i < data.exhibitDatas.length; i++) {
          // 停用启用
          if (data.exhibitDatas[i].status == 1) {
            data.exhibitDatas[i].isStatus = true
          } else {
            data.exhibitDatas[i].isStatus = false
          }
        }
        this.tableData = data.exhibitDatas
        this.totalCount = data.recordCount
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }
  // 初始化switch
  initSwitch() {
    var that = this
    $('.isStatus').bootstrapSwitch({
      //初始化按钮
      onText: '正常',
      offText: '停止',
      onColor: 'primary',
      offColor: 'warning',
      onSwitchChange: function (event, state) {
        if (state == true) {
          that.checkStatus('1', event.target.id)
        } else {
          that.checkStatus('2', event.target.id)
        }
      }
    })
  }
  //是否启用
  checkStatus(check, id) {
    var dataSource = {
      id: id,
      status: check
    }
    this.jsonApiService.http_obj('maintenance/enableRepairPoint.html', dataSource).subscribe(data => {
      if (data.success) {
        this.load()
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }
  showSiteMap(modal) {
    modal.show()
    this.initSiteMap()
  }
  // 新增
  tableAdd(modal) {
    this.pageType = '新增'
    // 重新获取非站点仓库
    this.getWarehouseList()
    this.repairPonitFrom = {
      id: undefined,
      repairPointName: '',
      warehouseId: '', // 非站点仓库
      companyArrays: [],
      companyId: '',
      userName: '',
      userId: '',
      linkMan: '',
      linkPhone: '',
      employNumber: '',
      startTime: '08:30',
      endTime: '20:00',
      address: '',
      lng: '',
      lat: '',
      repairInfo: [{ bookedNum: 0, num: 0, startTime: '08:30', endTime: '20:00' }],
      radius: '',
      provinceId: '',
      provinceName: ''
    }
    this.clearTimeArr()

    $('#workStartTime').val(this.repairPonitFrom.startTime)
    $('#workEndTime').val(this.repairPonitFrom.endTime)
    this.delLinkManFrom()
    $('#repairPointFrom').data('bootstrapValidator').resetForm()
    $('#hint').attr('style', 'display:none')
    $('#suggestId').val('')
    this.MAP.clearOverlays()
    this.points = []
    this.MAP.centerAndZoom(new BMap.Point(116.404, 39.915), 15)
    modal.show()
  }
  // 编辑
  tableEdit(row, modal) {
    const that = this
    this.clearTimeArr()
    this.repairPonitFrom.id = row.id
    this.pageType = '编辑'
    that.points = []
    modal.show()
    this.jsonApiService.http_obj('maintenance/findById.html', { id: row.id }).subscribe(data => {
      if (data.success) {
        that.MAP.clearOverlays()
        for (let key in this.repairPonitFrom) {
          this.repairPonitFrom[key] = data.data[key]
          $('#workStartTime').val(data.data['startTime'])
          $('#workEndTime').val(data.data['endTime'])
          if (key == 'userId' && this.userList) {
            $('#linkManSelect2').val(data.data[key]).trigger('change')
          }
          if (key == 'repairInfo') {
            this.repairPonitFrom[key] = this.repairPonitFrom[key] == '' ? [] : this.repairPonitFrom[key]
          }
        }
        if (this.repairPonitFrom.lng && this.repairPonitFrom.lat) {
          let point = toMapPoint({ lng: this.repairPonitFrom.lng, lat: this.repairPonitFrom.lat })
          let timer2 = setTimeout(() => {
            // that.MAP.centerAndZoom(new BMap.Point(point.lng, point.lat));
            that.markerMap(point, false)
            clearTimeout(timer2)
            timer2 = null
          }, 200)
        } else {
          that.MAP.centerAndZoom(new BMap.Point(116.404, 39.915), 15)
        }
        $('#suggestId').val('')
        $('#repairPointFrom').data('bootstrapValidator').resetForm()
        $('#hint').attr('style', 'display:none')

        if (this.repairPonitFrom.companyArrays.length > 0) {
          this.repairPonitFrom.companyId = this.repairPonitFrom.companyArrays.map(item => item.companyId)
          this.getAddressMsg(this.repairPonitFrom.companyId)
        } else {
          this.clearMarker('服务公司') //清空原有的定位数据
        }

        // 打开地图
        // this.showMap();
      }
    })
  }
  // 关闭弹窗
  modalClose(modal) {
    modal.hide()
    this.repairPonitFrom = {
      id: undefined,
      repairPointName: '',
      warehouseId: '', // 非站点仓库
      companyArrays: [],
      companyId: '',
      userName: '',
      userId: '',
      linkMan: '',
      linkPhone: '',
      employNumber: '',
      startTime: '',
      endTime: '',
      address: '',
      lng: '',
      lat: '',
      repairInfo: [],
      radius: '',
      provinceId: '',
      provinceName: ''
    }
    this.clearTimeArr()
    $('#workStartTime').val('')
    $('#workEndTime').val('')
    this.delLinkManFrom()
    $('#repairPointFrom').data('bootstrapValidator').resetForm()
  }
  // 清空时间区间选择的
  clearTimeArr() {
    this.myTimezoneList = []
    $('#handEndTime').datetimepicker('setStartDate', null)
    $('#handStartTime').datetimepicker('setStartDate', null)
    $('#handStartTime').datetimepicker('setEndDate', null)
    $('#handStartTime').val('')
    $('#handEndTime').val('')
    this.oneZoneCarNumByHand = ''
  }
  // 站点提交
  repairPointSubmit(modal) {
    const that = this
    $('#repairPointFrom').bootstrapValidator('validate') //开启验证
    if (this.repairPonitFrom.repairInfo.length == 0) {
      $('#timeZone').val('').change()
    } else {
      $('#timeZone').val('123').change()
    }
    // if (this.repairPonitFrom.radius == 0 || this.repairPonitFrom.radius == '') {
    //     this.jsonApiService.message('围栏半径不允许为空')
    //     return
    // }
    if (this.pageType == '编辑') {
      let timer = setTimeout(() => {
        let isValid = $('#repairPointFrom').data('bootstrapValidator').isValid() //验证是否通过
        if (isValid) {
          const params = { ...this.repairPonitFrom }
          delete params.warehouseId
          if (!params.lng || !params.lat) {
            params.lng = ''
            params.lat = ''
          }
          let reqdata = JSON.parse(JSON.stringify(params))
          reqdata.repairInfo = JSON.stringify(reqdata.repairInfo)
          this.jsonApiService.http_obj('maintenance/updateRepairPoint.html', reqdata).subscribe(data => {
            this.jsonApiService.message(data.message)
            if (data.success) {
              this.load()
              this.modalClose(modal)
            }
          })
        }
        clearTimeout(timer)
        timer = null
      }, 1000)
    } else {
      let isValid = $('#repairPointFrom').data('bootstrapValidator').isValid() //验证是否通过
      if (isValid) {
        let reqdata = JSON.parse(JSON.stringify(this.repairPonitFrom))
        reqdata.repairInfo = JSON.stringify(reqdata.repairInfo)
        this.jsonApiService.http_obj('maintenance/updateRepairPoint.html', reqdata).subscribe(data => {
          this.jsonApiService.message(data.message)
          if (data.success) {
            this.load()
            this.modalClose(modal)
          }
        })
      }
    }
  }
  // 站点数据
  initAllRepairPoint() {
    var that = this
    return new Promise(function (resolve, reject) {
      that.jsonApiService.http('maintenance/getRepairPointInfo.html', null).subscribe(data => {
        if (data.success) {
          var repairPointList = data.data
          var selectdata = []
          for (var i = 0; i < repairPointList.length; i++) {
            var obj = {
              id: repairPointList[i].id,
              text: repairPointList[i].repairPointName
            }
            selectdata[i] = obj
          }
        }
        that.repairPointList = selectdata
        resolve(true)
      })
    })
  }
  // 项目实施人员数据
  initAllUser() {
    const that = this
    return new Promise(function (resolve, reject) {
      that.jsonApiService.http('user/getUserList.html', null).subscribe(data => {
        const selectData = []
        const selectRepairUserList = []
        if (data.success) {
          const datas = data.data
          for (let i = 0; i < datas.length; i++) {
            const user = datas[i]
            const obj = {
              id: user.id,
              text: user.name + '-' + user.userName + (user.phone ? '-' + user.phone : ''),
              name: user.name,
              userName: user.userName,
              phone: user.phone
            }
            selectData.push(obj)
            const repairObj = {
              id: user.id,
              text: user.name + '-' + user.userName + (user.phone ? '-' + user.phone : '')
            }
            selectRepairUserList.push(repairObj)
          }
        }
        that.userList = selectData
        that.repairUserList = selectRepairUserList
        resolve(true)
      })
    })
  }
  // 责任人配置
  initLinkManSelect2() {
    let that = this
    // 责任人-form参数
    $('#linkManSelect2')
      .select2({
        language: 'zh-CN',
        placeholder: '请选择',
        allowClear: true,
        data: this.userList
      })
      .on('select2:select', function (e) {
        var data = e.params.data
        $('#linkManInput').val(data.text).change()
        that.repairPonitFrom.linkMan = data.name
        that.repairPonitFrom.userName = data.userName
        that.repairPonitFrom.userId = data.id
        that.repairPonitFrom.linkPhone = data.phone
      })
  }
  // 站点配置
  initRepairPointSelect2() {
    let that = this
    // 站点-查询条件
    $('#repairPointSelect2')
      .select2({
        language: 'zh-CN',
        placeholder: '请选择',
        allowClear: true,
        data: this.repairPointList
      })
      .on('select2:select', function (e) {
        var data = e.params.data
        that.tableParam.repairPointName = data.text
      })
  }
  // 删除责任人
  delLinkManFrom() {
    this.repairPonitFrom.userName = ''
    this.repairPonitFrom.linkMan = ''
    //采用简单粗暴的方法清除;官方推荐的方法失效
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#linkManSelect2').val('')
    $('#select2-linkManSelect2-container').empty()
    $('#select2-linkManSelect2-container').attr('title', '')
    $('#select2-linkManSelect2-container').prepend(str)
  }
  // 删除站点-查询
  delRepairPoint() {
    this.tableParam.repairPointName = ''
    //采用简单粗暴的方法清除;官方推荐的方法失效
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#repairPointSelect2').val('')
    $('#select2-repairPointSelect2-container').empty()
    $('#select2-repairPointSelect2-container').attr('title', '')
    $('#select2-repairPointSelect2-container').prepend(str)
  }
  //根据厂区请求厂区坐标以及区域信息
  getAddressMsg(ids) {
    const that = this
    this.jsonApiService.http_obj(`maintenance/getAddressMsg.html`, { ids }).subscribe(data => {
      if (data.success) {
        that.repairPonitFrom.provinceId = data.data.provinceId
        that.repairPonitFrom.provinceName = data.data.provinceName
        //数组打点
        if (data.data.companyAddresses.length > 0) {
          that.companyListMarker(data.data.companyAddresses)
        } else {
          that.clearMarker('服务公司') //清空原有的定位数据
        }
      } else {
        that.jsonApiService.message(data.message)
      }
    })
  }
  //数组打点
  companyListMarker(companyAddresses) {
    const that = this
    const companyMarkerList = JSON.parse(JSON.stringify(companyAddresses))
    //先清空
    that.clearMarker('服务公司').then(() => {
      for (let i = 0; i < companyMarkerList.length; i++) {
        if (companyMarkerList[i].lng && companyMarkerList[i].lat) {
          let repairPoint = toMapPoint(companyMarkerList[i])
          let point = new BMap.Point(companyMarkerList[i].lng, companyMarkerList[i].lat)
          var opts = {
            position: point, // 指定文本标注所在的地理位置
            offset: new BMap.Size(-10, -25) //设置文本偏移量
          }
          var labelText = new BMap.Label(companyMarkerList[i].companyName, opts) // 创建文本标注对象
          labelText.setStyle({
            padding: '5px',
            fontSize: '12px',
            color: '#000',
            border: '1px solid raba(0,0,0,0)',
            fontFamily: '微软雅黑',
            backgroundColor: '0.05'
          })
          let marker = new BMap.Marker(point, {
            icon: new BMap.Icon('assets/img/trackImage/company.png', new BMap.Size(34, 44)),
            title: '服务公司:' + companyMarkerList[i].companyName
          }) // 创建marker点
          marker.setLabel(labelText)
          that.MAP.addOverlay(marker)
          that.points.push(point)
          if (!that.repairPonitFrom.lng && !that.repairPonitFrom.lat) {
            let timer3 = setTimeout(() => {
              that.MAP.setViewport(that.points) //调整视野
              clearTimeout(timer3)
              timer3 = null
            }, 100)
          }
        }
      }
    })
  }
  // 初始化地图
  MAP: any
  SITEMAP: any
  mapSize: any = 14
  points: any = [] //所有point的集合
  initMap() {
    let that = this
    var map = new BMap.Map('baiduMap', { enableMapClick: false })
    let point = new BMap.Point(116.404, 39.915) //创建点坐标
    map.centerAndZoom(point, this.mapSize) //初始化地图，设置中心点坐标和地图级别
    map.addEventListener('zoomend', function () {
      that.mapSize = this.getZoom()
    })
    map.enableScrollWheelZoom(true)
    map.addEventListener('click', function (e) {
      //先清空
      that.clearMarker('站点名称').then(() => {
        // let point = e.point;
        var point = new BMap.Point(e.point.lng, e.point.lat)
        // if (that.repairPonitFrom.repairPointName) {
        var opts = {
          position: point, // 指定文本标注所在的地理位置
          offset: new BMap.Size(0, 0) //设置文本偏移量
        }
        var labelText = new BMap.Label(that.repairPonitFrom.repairPointName, opts) // 创建文本标注对象
        labelText.setStyle({
          padding: '5px',
          fontSize: '12px',
          color: '#000',
          border: '1px solid raba(0,0,0,0)',
          fontFamily: '微软雅黑',
          backgroundColor: '0.05',
          maxWidth: 'none',
          transform: 'translate(-35%, -100%)'
        })
        // }
        const markerIcon = new BMap.Icon('assets/img/coef_config.png', new BMap.Size(25, 25))
        markerIcon.setImageSize(new BMap.Size(25, 25))
        const marker = new BMap.Marker(point, {
          icon: markerIcon,
          title: '站点名称:' + that.repairPonitFrom.repairPointName
        }) // 创建marker点
        marker.setLabel(labelText)
        that.MAP.addOverlay(marker)
        // that.points.push(point)
        let repairPoint = toWGS84(point)
        that.repairPonitFrom.lng = repairPoint.lng.toFixed(7)
        that.repairPonitFrom.lat = repairPoint.lat.toFixed(7)
        // that.MAP.setViewport(that.points);　//调整视野
        //当半径存在
        if (that.repairPonitFrom.radius) {
          that.updateRadius(that.repairPonitFrom.radius)
        }
        //根据经纬度查询对应的地址
        that.jsonApiService
          .http_obj('region/getAddressByLocationV2.html', { lng: repairPoint.lng, lat: repairPoint.lat })
          .subscribe(data => {
            if (data.success) {
              that.repairPonitFrom.address = data.data.address
              $('#repairPointFrom').bootstrapValidator('updateStatus', 'address', 'NOT_VALIDATED')
              $('#suggestId').val(data.data.address)
            }
          })
      })
    })
    this.initBmapAutoSearch(map)
    this.MAP = map
  }
  siteMapPoint: any = []
  // 初始化站点地图
  initSiteMap() {
    this.mapParam = {
      companyId: '',
      provinceId: ''
    }
    $('#companyTree2 .tree_company_input').val('')
    $('#companyTree3 .tree_company_input').val('')
    let siteMap = new BMap.Map('siteMap', { enableMapClick: false })
    let point = new BMap.Point(116.404, 39.915) //创建点坐标
    siteMap.centerAndZoom(point, this.mapSize) //初始化地图，设置中心点坐标和地图级别
    siteMap.enableScrollWheelZoom(true)
    this.SITEMAP = siteMap
    this.querySiteMapData()
  }
  // 获取站点地图数据
  querySiteMapData() {
    let data = {
      companyId: this.mapParam.companyId,
      provinceId: this.mapParam.provinceId
    }
    this.SITEMAP.clearOverlays()
    if (this.markerClusterer) this.markerClusterer.clearMarkers()
    this.jsonApiService.http_obj('maintenance/getRepairPointInfo.html', data).subscribe(data => {
      if (data.success && data.data.length) {
        this.siteMapPoint = data.data
        this.renderSiteMapPoints()
      }
    })
  }
  markerClusterer: any = null
  // 渲染站点地图marker
  renderSiteMapPoints() {
    // 过滤不含经纬度的点
    let sitePoints = this.siteMapPoint.filter(v => v.lng && v.lat)
    // 点集合
    let points = []
    // marker集合
    let markers = []

    for (let i = 0; i < sitePoints.length; i++) {
      const st = sitePoints[i]
      const bmap_pt = toMapPoint({ lng: st.lng, lat: st.lat })
      const pt = new BMap.Point(bmap_pt.lng, bmap_pt.lat)
      const marker = new BMap.Marker(pt)
      const markerName = st.companyArrays[0].companyName
      const labelOpts = {
        position: pt,
        offset: new BMap.Size(0, 0)
      }
      // 设置label
      const label = new BMap.Label(markerName, labelOpts)
      label.setStyle({
        color: '#fff',
        backgroundColor: 'rgba(0,0,0,.5)',
        padding: '2px 10px',
        border: 'none',
        borderRadius: '4px',
        maxWidth: 'none',
        transform: 'translate(-40%, -100%)'
      })
      marker.setLabel(label) // 绑定label到marker上

      const infoWindowOpts = {
        width: 200, // 信息窗口宽度
        height: 0, // 信息窗口高度
        title: '站点信息' // 信息窗口标题
      }
      var infoWindowMse = `<div class="infoBox"><a></a><div class="content">
                    <ul>
                      <li><span class="leftSpan">站点名称：</span><span class="rightSpan">${st.repairPointName
        }</span></li>
                      <li><span class="leftSpan">服务厂区：</span><span class="rightSpan">${markerName}</span></li>
                      <li><span class="leftSpan">负责人员：</span><span class="rightSpan">${st.linkMan || '--'
        }</span></li>
                      <li><span class="leftSpan">工作时间：</span><span class="rightSpan">${st.startTime}-${st.endTime
        }</span></li>
                      <li><span class="leftSpan">站点地址：</span><span class="rightSpan">${st.address || '--'
        }</span></li>
                    </ul>
                  </div></div>`
      const infoWindow = new BMap.InfoWindow(infoWindowMse, infoWindowOpts) // 创建信息窗口对象
      marker.addEventListener('click', () => {
        this.SITEMAP.openInfoWindow(infoWindow, pt) // 开启信息窗口
      })
      points.push(pt)
      // markers.push(marker)
      this.SITEMAP.addOverlay(marker)
    }
    // this.markerClusterer = new BMapLib.MarkerClusterer(this.SITEMAP, {markers: markers});
    setTimeout(() => {
      this.SITEMAP.setViewport(points)
    }, 200)
  }
  // 百度地图自动检索功能
  initBmapAutoSearch(map) {
    const that = this
    //建立一个自动完成的对象
    let autoSearch = new BMap.Autocomplete({ input: 'suggestId', location: map })
    autoSearch.addEventListener('onhighlight', function (e) {
      //鼠标放在下拉列表上的事件
      var str = ''
      var _value = e.fromitem.value
      var value = ''
      if (e.fromitem.index > -1) {
        value = _value.province + _value.city + _value.district + _value.street + _value.business
      }
      str = 'FromItem<br />index = ' + e.fromitem.index + '<br />value = ' + value
      value = ''
      if (e.toitem.index > -1) {
        _value = e.toitem.value
        value = _value.province + _value.city + _value.district + _value.street + _value.business
      }
      str += '<br />ToItem<br />index = ' + e.toitem.index + '<br />value = ' + value
      document.getElementById('searchResultPanel').innerHTML = str
    })
    let myValue
    // 创建地址解析器实例
    var myGeo = new BMap.Geocoder()
    // 将地址解析结果显示在地图上,并调整地图视野

    autoSearch.addEventListener(
      'onconfirm',
      function (e) {
        //鼠标点击下拉列表后的事件
        let _value = e.item.value
        myValue = _value.province + _value.city + _value.district + _value.street + _value.business
        document.getElementById('searchResultPanel').innerHTML =
          'onconfirm<br />index = ' + e.item.index + '<br />myValue = ' + myValue
        const local = new BMap.LocalSearch(map, {
          //智能搜索
          onSearchComplete: function (result) {
            const point1 = JSON.parse(JSON.stringify(local.getResults().getPoi(0).point))
            const point2 = JSON.parse(JSON.stringify(local.getResults().getPoi(0).point))
            //根据经纬度查询对应的地址
            const repairPoint = toWGS84(point2)
            that.jsonApiService
              .http_obj('region/getAddressByLocationV2.html', { lng: repairPoint.lng, lat: repairPoint.lat })
              .subscribe(data => {
                if (data.success) {
                  that.repairPonitFrom.address = data.data.address
                  $('#repairPointFrom').bootstrapValidator('updateStatus', 'address', 'NOT_VALIDATED')
                  that.markerMap(point1, true)
                }
              })
          }.bind(this)
        })
        local.search(myValue)
      }.bind(this)
    )
  }

  /**
   * 时间区间选择的方法
   */
  timeArrmodalClose(modal) {
    // 重置表单
    this.addStartTimeQuick = ''
    // $('#handStartTime').val('');
    // $('#handEndTime').val('');
    // this.oneZoneCarNumByHand = ''
    modal.hide()
  }
  // 打开选择时间区间的modal
  showSelectTime(modal, isOverSelectTime) {
    this.editOverall = false //先重置
    this.isOverSelectTime = isOverSelectTime // 是否是全局的
    // 重置
    this.addStartTimeQuick = ''
    $('#handStartTime').datetimepicker(
      'setStartDate',
      this.repairPonitFrom.startTime ? this.repairPonitFrom.startTime : null
    )
    // 查询单个的编辑
    if (!isOverSelectTime) {
      this.myTimezoneList = this.repairPonitFrom.repairInfo
      if (this.myTimezoneList && this.myTimezoneList.length > 0) {
        let endTime = this.repairPonitFrom.repairInfo[this.repairPonitFrom.repairInfo.length - 1].endTime
        this.setStartTimeLimit(endTime)
      } else {
        // 重置表单
        this.clearTimeArr()
      }
    }
    // 点开的是全局默认配置按钮
    if (isOverSelectTime) {
      this.editOverall = true
      // 重置表单
      this.clearTimeArr()
      this.addStartTimeQuick = ''
      let reqData = ''
      this.jsonApiService.http_obj('appointmentRepairCar/defaultDateList.html', reqData).subscribe(data => {
        if (data.success) {
          let arr = data.data
          this.myTimezoneList = arr
          if (arr.length > 0) {
            this.editOverall = true
          } else {
            this.editOverall = false
          }
        }
      })
    }
    modal.show()
  }

  editItem: number = null // 选中表格的位置下标
  @ViewChild('autofocusInput') autofocusRef: ElementRef
  handledClick(row: any, index: number) {
    console.log(row, index)
    this.editItem = index
    setTimeout(() => {
      this.autofocusRef.nativeElement.focus()
    }, 100)
  }
  // 表格输入框失去焦点
  handleBlur(row: any) {
    this.editItem = null
  }

  // 一小时快速选择
  oneHourSplit() {
    this.quickSplitTime(1)
    this.setStartTimeLimit(this.myTimezoneList[this.myTimezoneList.length - 1].endTime)
  }
  // 两小时快速选择
  twoHourSplit() {
    this.quickSplitTime(2)
    this.setStartTimeLimit(this.myTimezoneList[this.myTimezoneList.length - 1].endTime)
  }
  quickSplitTime(step) {
    let startTime = '08:30'
    let endTime = '19:30'
    if (!this.isOverSelectTime) {
      if (this.repairPonitFrom.startTime) {
        startTime = this.repairPonitFrom.startTime
      }
      if (this.repairPonitFrom.endTime) {
        endTime = this.repairPonitFrom.endTime
      }
    }
    let num = this.addStartTimeQuick ? this.addStartTimeQuick : 5
    let arr = []
    let m = startTime.split(':')[1]
    let startHour = startTime.split(':')[0]
    for (let i = 0; i < 24; i++) {
      // 结束时间为一个小时
      let endHour: any = Number(startHour) + step
      endHour = endHour < 10 ? '0' + endHour : endHour
      // 18:30 19:30
      if (startHour >= endTime.split(':')[0]) {
        break
      }
      let st = startHour + ':' + m
      let et = endHour + ':' + m
      let obj = { startTime: st, endTime: et, num: num }
      arr.push(obj)
      // 循环完就加1
      startHour = endHour
    }
    // 比较最后一个结束时间是否大于下班时间  大于的话就去掉
    let lastET = Number(arr[arr.length - 1].endTime.split(':').join(''))
    let endTimeStr = Number(endTime.split(':').join(''))
    if (lastET > endTimeStr) {
      arr.splice(arr.length - 1, 1)
    }
    this.myTimezoneList = arr
  }
  // 一键同步默认
  toSameOverall() {
    // 重置表单
    this.clearTimeArr()
    this.addStartTimeQuick = ''
    let reqData = ''
    this.jsonApiService.http_obj('appointmentRepairCar/defaultDateList.html', reqData).subscribe(data => {
      if (data.success) {
        let arr = data.data
        this.myTimezoneList = arr
        this.setStartTimeLimit(arr[arr.length - 1].endTime)
      }
    })
  }
  // 开始时间选择框的限制  输入一个 hh：mm时间类型   然后会给datePicker设置开始时间限制
  setStartTimeLimit(myStartTime) {
    // 设置开始时间的限制
    let date = new Date()
    var year = date.getFullYear()
    var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
    var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
    let nextStartTime = year + '-' + month + '-' + day + ' ' + myStartTime + ':00'
    let nextDate = new Date(nextStartTime)
    nextDate.setTime(nextDate.getTime() - 1000)
    var nextTime = common.getTimeMmss(nextDate)
    $('#handStartTime').datetimepicker('setStartDate', nextTime)
    $('#handStartTime').datetimepicker('setEndDate', null)
  }
  // 重新配置全局的时间
  resetOverAllTime() {
    this.editOverall = false
    this.myTimezoneList = []
  }
  // 初始化时间选择
  initTimeArr() {
    let that = this
    System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
      System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
        $('#handStartTime')
          .datetimepicker({
            //时间插件
            format: 'hh:ii',
            language: 'zh-CN',
            autoclose: true,
            minView: 0,
            minuteStep: 5,
            startView: 1
          })
          .on('changeDate', function (e) {
            var date = e.date
            // 最少要隔一个小时
            date.setTime(date.getTime() + 59 * 60 * 1000)
            var time = common.getTimeMmss(date)

            // that.repairPonitFrom.startTime = $("#workStartTime").val();
            $('#handEndTime').datetimepicker('setStartDate', time)
            $('#handStartTime').change()
          })
        $('#handEndTime')
          .datetimepicker({
            //时间插件
            format: 'hh:ii',
            language: 'zh-CN',
            autoclose: true,
            minView: 0,
            minuteStep: 5,
            startView: 1
          })
          .on('changeDate', function (e) {
            var date = e.date
            // 最少要隔一个小时
            date.setTime(date.getTime() - 59 * 60 * 1000)
            var time = common.getTimeMmss(date)

            // that.repairPonitFrom.endTime = $("#workEndTime").val();
            $('#handStartTime').datetimepicker('setEndDate', time)
            $('#handEndTime').change()
          })

        $('#workStartTime')
          .datetimepicker({
            //时间插件
            format: 'hh:ii',
            language: 'zh-CN',
            autoclose: true,
            minView: 0,
            minuteStep: 5,
            startView: 1
          })
          .on('changeDate', function (e) {
            var date = e.date
            var time = common.getTimeMmss(date)
            that.repairPonitFrom.startTime = $('#workStartTime').val()
            $('#workEndTime').datetimepicker('setStartDate', time)
            $('#workStartTime').change()
          })
        $('#workEndTime')
          .datetimepicker({
            //时间插件
            format: 'hh:ii',
            language: 'zh-CN',
            autoclose: true,
            minView: 0,
            minuteStep: 5,
            startView: 1
          })
          .on('changeDate', function (e) {
            var date = e.date
            var time = common.getTimeMmss(date)
            that.repairPonitFrom.endTime = $('#workEndTime').val()
            $('#workStartTime').datetimepicker('setEndDate', time)
            $('#workEndTime').change()
          })
      })
    })
  }
  // 手动添加时间区间按钮
  addTimeByHand() {
    if ($('#handStartTime').val() == '') {
      this.jsonApiService.message('请选择开始时间')
      return
    } else if ($('#handEndTime').val() == '') {
      this.jsonApiService.message('请选择结束时间')
      return
    }

    // 时间
    let startTime = $('#handStartTime').val()
    let endTime = $('#handEndTime').val()
    // 默认数量为0个
    let num = $('#handNum').val() ? $('#handNum').val() : 0
    let obj = { startTime: startTime, endTime: endTime, num: num }
    // 设置开始时间的限制
    let date = new Date()
    var year = date.getFullYear()
    var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
    var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
    let nextStartTime = year + '-' + month + '-' + day + ' ' + endTime + ':00'
    let nextDate = new Date(nextStartTime)
    nextDate.setTime(nextDate.getTime() - 1000)
    var nextTime = common.getTimeMmss(nextDate)
    $('#handStartTime').datetimepicker('setStartDate', nextTime)
    $('#handStartTime').datetimepicker('setEndDate', null)
    // 结束时间必须在一个小时后
    nextDate.setTime(nextDate.getTime() + 59 * 60 * 1000)
    var nextEndTime = common.getTimeMmss(nextDate)
    $('#handEndTime').datetimepicker('setStartDate', nextEndTime)
    $('#handStartTime').val(endTime)
    $('#handEndTime').val('')
    this.myTimezoneList.push(obj)
  }
  resetTimeZoneList() {
    this.clearTimeArr()
  }
  // 时间选择提交
  timeSelectSubmit(modal) {
    // 全局的配置
    if (this.isOverSelectTime) {
      if (this.myTimezoneList && this.myTimezoneList.length == 0) {
        this.jsonApiService.message('请添加时间区间')
      } else {
        let reqData = 'defaultDateJson=' + JSON.stringify(this.myTimezoneList)
        this.jsonApiService.http('appointmentRepairCar/saveDefaultDate.html', reqData).subscribe(data => {
          this.jsonApiService.message(data.message)
          if (data.success) {
            this.modalClose(modal)
          }
        })
      }
    } else {
      modal.hide()
      // 单个的配置
      this.repairPonitFrom.repairInfo = JSON.parse(JSON.stringify(this.myTimezoneList))
      if (this.repairPonitFrom.repairInfo.length > 0) {
        $('#timeZone').val('123').change()
      } else {
        $('#timeZone').val('').change()
      }
    }
  }

  //监听地址栏输入值的改变
  updateAddress() {
    const that = this
    if (!that.repairPonitFrom.repairPointName) {
      that.jsonApiService.message('请先输入站点名称')
      return
    }
    if (!that.repairPonitFrom.address) {
      that.jsonApiService.message('请先输入地址')
      return
    }
    $('#suggestId').val(that.repairPonitFrom.address)
  }

  //地图打点 isConvert 是否需要转换
  markerMap(pointValue, isConvert) {
    const that = this
    //先清空
    that.clearMarker('站点名称').then(() => {
      let point = new BMap.Point(pointValue.lng, pointValue.lat)
      var opts = {
        position: point, // 指定文本标注所在的地理位置
        offset: new BMap.Size(0, 0) //设置文本偏移量
      }
      var labelText = new BMap.Label(that.repairPonitFrom.repairPointName, opts) // 创建文本标注对象
      labelText.setStyle({
        padding: '5px',
        fontSize: '12px',
        color: '#000',
        border: '1px solid raba(0,0,0,0)',
        fontFamily: '微软雅黑',
        backgroundColor: '0.05',
        maxWidth: 'none',
        transform: 'translate(-35%, -100%)'
      })
      const markerIcon = new BMap.Icon('assets/img/coef_config.png', new BMap.Size(25, 25))
      markerIcon.setImageSize(new BMap.Size(25, 25))
      let marker = new BMap.Marker(point, {
        icon: markerIcon,
        title: '站点名称:' + that.repairPonitFrom.repairPointName
      }) // 创建marker点
      marker.setLabel(labelText)
      that.MAP.addOverlay(marker)
      that.points.push(point)

      if (isConvert) {
        let repairPoint = toWGS84({ lng: pointValue.lng, lat: pointValue.lat })
        that.repairPonitFrom.lng = repairPoint.lng.toFixed(7)
        that.repairPonitFrom.lat = repairPoint.lat.toFixed(7)
      }
      if (that.repairPonitFrom.radius) {
        that.updateRadius(that.repairPonitFrom.radius)
      } else {
        that.MAP.setViewport(that.points) //调整视野
      }
    })
  }

  //监听半径
  updateRadius(event) {
    const that = this
    const reg = /^\+?[1-9][0-9]*$/
    let railStyle = {
      strokeColor: 'blue',
      fillColor: 'red',
      strokeWeight: 1,
      strokeOpacity: 0.2,
      fillOpacity: 0.2
    }
    var overlays = that.MAP.getOverlays()
    if (event) {
      if (!reg.test(event)) {
        that.jsonApiService.message('围栏半径格式不正确')
        return
      }
      // console.log(overlays, 'radius')
      const radius = parseInt(event)
      that.repairPonitFrom.radius = radius //赋值radius
      if (that.repairPonitFrom.lng && that.repairPonitFrom.lat) {
        that.clearMarker('').then(() => {
          let pointValue = toMapPoint({ lng: that.repairPonitFrom.lng, lat: that.repairPonitFrom.lat })
          var point = new BMap.Point(pointValue.lng, pointValue.lat)
          var circle = new BMap.Circle(point, radius, railStyle)
          that.MAP.addOverlay(circle) // 增加圆

          let circlePaths = that.points.concat(circle.getPath())
          that.points = JSON.parse(JSON.stringify(circlePaths))
          let timer4 = setTimeout(() => {
            that.MAP.setViewport(that.points) //调整视野
            clearTimeout(timer4)
            timer4 = null
          }, 150)
        })
      }
    } else {
      that.clearMarker('')
      // console.log(overlays, 'clearMarker,radius')
    }
  }
  //清除坐标点 type为address则是 地址   为company则是厂区  两者都没有则是圆
  clearMarker(type) {
    const that = this
    return new Promise(function (resolve, reject) {
      var overlays = that.MAP.getOverlays()
      // console.log(overlays, 'overlays1')
      if (overlays.length > 0) {
        for (let i = 0; i < overlays.length; i++) {
          if (type) {
            if (overlays[i].z.title && overlays[i].z.title.indexOf(type) != -1) {
              that.points.splice(i, 1)
              that.MAP.removeOverlay(overlays[i])
            }
          } else {
            if (overlays[i].xa) {
              that.points.splice(i, 1)
              that.MAP.removeOverlay(overlays[i])
            }
          }
        }
        // console.log(overlays, 'overlays2')
      }
      resolve(true)
    })
  }

  /**
   * 人员管理
   */
  isShowAdd: boolean = false
  isShowDel: boolean = false
  //初始化权限按钮
  initBtn() {
    var btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_wx:repair:point')))
    if (!btnData) {
      return
    }
    for (let item of btnData) {
      if (item.sourceKey === 'repairPoint:addBtn' && item.parentId) {
        this.isShowAdd = true
      }
      if (item.sourceKey === 'repairPoint:delBtn' && item.parentId) {
        this.isShowDel = true
      }
    }
  }
  rowId: any = '' //请求列表数据
  viewCarData: any = [] //车牌数据列表
  carNumberSubList: any = [] //请求的车辆数据
  userId: any = '' //查询出来的数据
  repairUserList: any = [] //所有维修人员列表
  //查看车辆列表
  viewPersonnel(row, modal) {
    this.rowId = row.id
    this.requestList()
    modal.show()
  }

  //请求站点人员列表
  requestList() {
    var reqdata = {
      id: this.rowId
    }
    this.jsonApiService.http_obj('maintenance/getRepairPonitMan.html', reqdata).subscribe(data => {
      if (data.success) {
        this.viewCarData = data.data
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }
  closeModal(modal) {
    modal.hide()
    this.mapParam = {
      companyId: '',
      provinceId: ''
    }
    $('#companyTree2 .tree_company_input').val('')
    $('#companyTree3 .tree_company_input').val('')
  }
  //初始化维修人员
  // initRepairUser() {
  //   var that = this
  //   return new Promise(function (resolve, reject) {
  //     that.jsonApiService.http('maintenance/userlist.html', null).subscribe(data => {
  //       if (data.success) {
  //         var userList = data.data
  //         var selectdata = []
  //         for (var i = 0; i < userList.length; i++) {
  //           var obj = {
  //             id: userList[i].id,
  //             text: userList[i].name + '-' + userList[i].userName + (userList[i].phone ? '-' + userList[i].phone : '')
  //           }
  //           selectdata[i] = obj
  //         }
  //       }
  //       that.repairUserList = selectdata
  //       resolve()
  //     })
  //   })
  // }
  // 站点配置
  initRepairUserSelect2() {
    let that = this
    // 站点-查询条件
    $('#patchSelect2')
      .select2({
        language: 'zh-CN',
        placeholder: '请选择',
        allowClear: true,
        data: this.repairUserList
      })
      .on('select2:select', function (e) {
        var data = e.params.data
        that.userId = data.id
      })
  }
  //擦除用户所选值
  delNumberSelect() {
    this.userId = ''
    //采用简单粗暴的方法清除;官方推荐的方法失效
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#patchSelect2').val('')
    $('#select2-patchSelect2-container').empty()
    $('#select2-patchSelect2-container').attr('title', '')
    $('#select2-patchSelect2-container').prepend(str)
  }

  //添加人员
  addViewList(modal) {
    var that = this
    modal.show()
    that.userId = ''
    $('#patchSelect2').val('').change()
    // that.clearSelect2($('#patchSelect2')) //清除Select中的数据
  }
  //清空select2
  clearSelect2(obj) {
    obj.empty()
    obj.prepend("<option value=''>请选择</option>")
  }
  //删除车辆
  deleteView(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
      let parameters = {
        id: this.rowId,
        userId: row.userId
      }
      this.jsonApiService.http_obj('maintenance/delEmp.html', parameters).subscribe(data => {
        this.jsonApiService.message(data.message)
        this.requestList()
        this.load()
      })
    })
  }

  //关闭
  viewClose(modal) {
    modal.hide()
  }
  //提交
  viewSubmit(modal) {
    if (!this.userId) {
      this.jsonApiService.message('请先添加实施人员')
      return
    }
    var reqdata = {
      userId: this.userId,
      id: this.rowId
    }

    this.jsonApiService.http_obj('maintenance/addEmp.html', reqdata).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        this.userId = ''
        this.requestList()
        this.load()
        modal.hide()
      }
    })
  }

  fileUp: string = ''
  fileToUpload: any = [] //上传文件回调参数
  // 显示导入的弹框
  showImportModal(modal) {
    modal.show()
  }
  // 关闭导入的弹框
  cancelUp(val) {
    val.hide()
    this.fileToUpload = []
  }
  //下载模板
  load_module() {
    common.exprotDataFile({}, 'param', config.BaseURL + 'maintenance/exportExcelData.html')
  }
  // 清空input type=file输入框的值
  clearFile() {
    this.fileUp = ''
  }

  //文件上传change回调
  fileChange(files) {
    console.log(files)
    // 这一层循环判断格式是否正确
    for (let index = 0; index < files.length; index++) {
      console.log(files.item(index))
      const isEXCEL =
        files.item(index).type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        files.item(index).type === 'application/vnd.ms-excel'
      if (!isEXCEL) {
        this.jsonApiService.message('上传文件只能是 excel格式!')
        return
      } else {
        let isSame = false
        //
        for (let i = 0; i < this.fileToUpload.length; i++) {
          if (this.fileToUpload[i].name == files.item(index).name) {
            this.jsonApiService.message('上传文件重复!')
            isSame = true
            break
          }
        }
        if (!isSame) {
          this.fileToUpload.push(files.item(index))
        }
      }
    }
  }

  //导入submit
  submitData(val) {
    if (this.fileToUpload.length == 0) {
      this.jsonApiService.message('请上传文件')
      return false
    }
    for (let i = 0; i < this.fileToUpload.length; i++) {
      let postParam = new FormData()
      postParam.append('file', this.fileToUpload[i])
      this.jsonApiService.form_http('maintenance/importExcelData.html', postParam).subscribe(data => {
        // this.jsonApiService.message("第["+i+"]份"+data.message);
        this.jsonApiService.message(data.message)
        if (data.success) {
          val.hide()
          this.fileToUpload = []
          this.load()
        } else {
          val.hide()
          this.fileToUpload = []
        }
      })
    }
  }

  // 数据导出
  exportData() {
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        repairPointName: this.tableParam.repairPointName,
        companyId: this.tableParam.companyId,
        pointPersonnel: this.tableParam.pointPersonnel,
        startTime: this.tableParam.startTime,
        endTime: this.tableParam.endTime,
        status: this.tableParam.status,
        searchKey: common.stringTrim(this.tableParam.searchKey),
        provinceName: this.tableParam.provinceName,
        provinceId: this.tableParam.provinceId
      },
      isExport: 1
    }
    common.exprotDataFile(data, 'gridPager', config.BaseURL + 'maintenance/list.html')
  }

  //高级功能
  seniorFunction(modal) {
    this.renewLoad = false
    modal.show()
  }
  //关闭高级功能弹窗
  seniorFunctionClose(modal) {
    modal.hide()
  }
  renewLoad = false //设置loading
  //更新
  seniorFunctionRenew() {
    this.renewLoad = true
    this.jsonApiService.http('maintenance/updatePointLngLat.html', {}, false).subscribe(data => {
      this.jsonApiService.message(data.message)
      this.renewLoad = false
    })
  }
  raius: any = null //半径
  radiusLoad = false //更新半径loading
  settingRadiusOptions = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      raiusNum: {
        validators: {
          notEmpty: {
            message: '请输入半径(米)'
          },
          digits: {
            message: '请输入正整数'
          },
          callback: {
            callback: function (value, validator, $field) {
              if (value) {
                if (!/^\+?[1-9][0-9]*$/.test(value)) {
                  return {
                    valid: false,
                    message: '请输入正整数'
                  }
                } else {
                  return true
                }
              } else {
                return {
                  valid: false,
                  message: '请输入半径(米)'
                }
              }
            }.bind(this)
          }
        }
      }
    }
  }
  //设置
  seniorFunctionSetup(modal) {
    $('#settingRadiusFrom').data('bootstrapValidator').resetForm()
    this.radiusLoad = false
    this.raius = null
    modal.show()
  }
  //关闭批量设置
  settingRadiusClose(modal) {
    modal.hide()
  }
  //提交批量设置半径
  settingRadiusSubmit(modal) {
    // if (!this.raius) {
    //   this.jsonApiService.message('半径不能为空或者0')
    //   return
    // }
    $('#settingRadiusFrom').bootstrapValidator('validate') //开启验证
    let isValid = $('#settingRadiusFrom').data('bootstrapValidator').isValid() //验证是否通过
    if (isValid) {
      this.radiusLoad = true
      this.jsonApiService
        .http_obj('maintenance/updatePointRadius.html', { radius: this.raius }, false)
        .subscribe(data => {
          this.jsonApiService.message(data.message)
          this.radiusLoad = false
          modal.hide()
        })
    }
  }

  // -------------- 门头照片管理部分 -------------- //
  doorPhotosList = []
  isViewPhotos = false
  viewer = null

  handlePhotosManage(row, modal, isView = false) {
    this.rowId = row.id
    this.doorPhotosList = row.doorPhotos
    this.isViewPhotos = isView
    modal.show()

    if (this.viewer) {
      this.viewer.destroy()
      this.viewer = null
    }
  }

  // 上传照片
  uploadImg(files: FileList) {
    if (this.viewer) {
      this.viewer.destroy()
      this.viewer = null
    }

    const file = files[0];

    const reqdata = new FormData();
    reqdata.append('describe', '门头照片');
    reqdata.append('businessType', '99');
    reqdata.append('type', '2'); //type 1获取相对路径  2获取绝对路径

    const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png';
    if (!isJPG) {
      this.jsonApiService.message('上传图片只能是 png, jpg, jpeg 格式!');
      return;
    }
    reqdata.append('files', file);

    this.jsonApiService.form_http("fileUpload/upload.html", reqdata).subscribe(data => {
      if (data.success) {
        console.log()
        const url = data.data[0]
        this.handleUploadPhotos(url, 0)
      }
    })

    for (let k = 0; k < $(".up").length; k++) {
      $(".up")[k].value = null;
    }
  }

  // 删除照片
  deleteImg(i) {
    if (this.viewer) {
      this.viewer.destroy()
      this.viewer = null
    }

    const url = this.doorPhotosList[i]
    this.handleUploadPhotos(url, 1)
  }

  handleUploadPhotos(url: string, type: 0 | 1) {
    const params = {
      recordId: this.rowId,
      operationType: type,
      doorPhotosUrls: url
    }

    this.jsonApiService
      .http_obj('maintenance/doorPhotosManage.html', params)
      .subscribe(data => {
        if (data.success && data.data) {
          this.doorPhotosList = data.data
          this.load()
        } else {
          this.jsonApiService.message(data.message)
        }
      })
  }

  // 点击图片放大查看
  bigImgClick() {
    // if (this.viewer) {
    //   this.viewer.destroy()
    //   this.viewer = null
    // }

    if (this.viewer) {
      this.viewer.show()
      return
    }

    const imgList = $(".imgFileList")[0];
    this.viewer = new Viewer(imgList, {
      url: 'src',
      title: function (image) {
        return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')';
      },
    });
  }
}
